class Node:
    def __init__(self, val):
        self.val = val
        self.next = None
    def __str__(self):
        return str(self.val) + str(self.next)


def add_two_numbers_2(h1: Node, h2: Node):
    l1, l2 = [], []
    while h1:
        l1.append(h1.val)
        h1 = h1.next
    while h2:
        l2.append(h2.val)
        h2 = h2.next

    result = []
    carry = 0
    if len(l1) > len(l2): l1, l2 = l2, l1
    while l1 and l2:
        n1 = l1.pop()
        n2 = l2.pop()
        carry, val = divmod((n1 + n2 + carry), 10)
        result.append(val)
    while l2:
        carry, val = divmod((l2.pop() + carry), 10)
        result.append(val)

    if carry:
        result.append(carry)

    dum_head = Node(-1)
    head = dum_head
    while result:
        node = Node(result.pop())
        head.next = node
        head = node
    return dum_head.next

def build_nodes(vals):
    nodes = [Node(val) for val in vals]
    for i in range(len(nodes)-1):
        nodes[i].next = nodes[i+1]
    return nodes[0]

print(add_two_numbers_2(build_nodes([7,2,4,3]), build_nodes([5,6,4])))
print(add_two_numbers_2(build_nodes([9,9]), build_nodes([1])))